/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AlteraDepartamento.java
 *
 * Created on Nov 29, 2011, 6:49:13 PM
 */

package janelas.busca;

import banco.Connect;
import janelas.altera.AlteraDepartamento;
import janelas.altera.AlteraJornal;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author eduardo
 */
public class BuscaJornal extends javax.swing.JFrame
{
    private Connect banco;
    private ArrayList<String[]> resultados;
    private ResultSetMetaData meta;

    /** Creates new form AlteraDepartamento */
    public BuscaJornal(Connect banco)
    {
        initComponents();
        this.banco = banco;
        resultados = new ArrayList();
        try
        {
            ResultSet rs = this.banco.query("SELECT idPR AS \"ID Jornal\", tituloPr AS \"Título do Jornal\", descricaoPr AS \"Descrição do Jornal\", idDe AS \"ID do Departamento\", duracaoJo AS \"Duração\", abrangenciaJo AS \"Abrangência\" FROM jornal");
            meta = rs.getMetaData();
            String[] columns = new String[meta.getColumnCount()];

            for (int i = 1 ; i <= meta.getColumnCount() ; i++)
            {
                columns[i-1] = meta.getColumnName(i);
            }

            while (rs.next())
            {
                String[] row = new String[meta.getColumnCount()];
                for (int i = 1; i <= meta.getColumnCount() ; i++)
                {
                    row[i-1]=rs.getString(i);
                }
                resultados.add(row);
            }

            String[][] dados = new String[resultados.size()][meta.getColumnCount()];
            for (int i = 0 ; i < resultados.size() ; i++)
            {
                dados[i] = resultados.get(i);
            }
            jTable1.setModel(new DefaultTableModel(dados,columns));
        }
        catch (Exception ex)
        {
            JOptionPane.showMessageDialog(null, "Ocorreu algum problema ao buscar. Confira o formato dos parâmetros", "Erro ao Buscar", JOptionPane.ERROR_MESSAGE);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Alteração/Remoção de Jornal");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setText("Título do Jornal:");

        jLabel2.setText("Descrição do Jornal:");

        jLabel3.setText("ID do Departamento:");

        jButton1.setText("Buscar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Alterar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Remover");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Sair");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 692, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 261, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jButton1)
                            .addComponent(jButton2)
                            .addComponent(jButton3)
                            .addComponent(jButton4))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton4)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        String consulta;
        int n = 0;
        consulta = "SELECT idPR AS \"ID Jornal\", tituloPr AS \"Título do Jornal\", descricaoPr AS \"Descrição do Jornal\", idDe AS \"ID do Departamento\", duracaoJo AS \"Duração\", abrangenciaJo AS \"Abrangência\" FROM jornal WHERE ";
        if (!(jTextField1.getText().trim().equals("")) && !(jTextField1.getText() == null))
        {
            n++;
            consulta = consulta + "tituloPr LIKE '%" + jTextField1.getText() + "%' AND ";
        }
        if (!(jTextField2.getText().trim().equals("")) && !(jTextField2.getText() == null))
        {
            n++;
            consulta = consulta + "descricaoPr LIKE '%" + jTextField2.getText() + "%' AND ";
        }
        if (!(jTextField3.getText().trim().equals("")) && !(jTextField3.getText() == null))
        {
            n++;
            consulta = consulta + "idDe = " + jTextField3.getText() + " AND ";
        }
        if (n==0)
        {
            consulta = consulta.substring(0, (consulta.length()-7));
        }
        else
        {
            consulta = consulta.substring(0, (consulta.length()-5));
        }
        System.out.println(consulta);
        resultados = new ArrayList();
        try
        {
            ResultSet rs = this.banco.query(consulta);
            meta = rs.getMetaData();
            String[] columns = new String[meta.getColumnCount()];

            for (int i = 1 ; i <= meta.getColumnCount() ; i++)
            {
                columns[i-1] = meta.getColumnName(i);
            }

            while (rs.next())
            {
                String[] row = new String[meta.getColumnCount()];
                for (int i = 1; i <= meta.getColumnCount() ; i++)
                {
                    row[i-1]=rs.getString(i);
                }
                resultados.add(row);
            }

            String[][] dados = new String[resultados.size()][meta.getColumnCount()];
            for (int i = 0 ; i < resultados.size() ; i++)
            {
                dados[i] = resultados.get(i);
            }

            jTable1.setModel(new DefaultTableModel(dados,columns));
        }
        catch (Exception ex)
        {
            Logger.getLogger(BuscaJornal.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        int i = jTable1.getSelectedRow();
        ArrayList<String> linha = new ArrayList();
        try
        {
            for (int j = 0 ; j < meta.getColumnCount(); j++)
            {
                linha.add(resultados.get(i)[j]);
            }
            AlteraJornal aJ = new AlteraJornal(linha, banco);
            aJ.setVisible(true);
            aJ.setResizable(false);
        }
        catch (SQLException ex)
        {
            Logger.getLogger(BuscaJornal.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        ArrayList<String> retorno = new ArrayList();
        int i = jTable1.getSelectedRow();
        try
        {
            for (int j = 0 ; j < meta.getColumnCount(); j++)
            {
                retorno.add(resultados.get(i)[j]);
            }
        }
        catch (SQLException ex)
        {
            Logger.getLogger(BuscaJornal.class.getName()).log(Level.SEVERE, null, ex);
        }
        try
        {
            if (JOptionPane.showConfirmDialog(null,"Deseja realmente remover o Jornal com ID = " + retorno.get(0) + "?", "Confirmação de Remoção", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
            {
                banco.update("DELETE FROM jornal WHERE idPr = " + retorno.get(0));
                JOptionPane.showMessageDialog(null, "Jornal removido com sucesso!", "Remoção bem Sucedida", JOptionPane.INFORMATION_MESSAGE);
            }
        }
        catch (Exception ex)
        {
            JOptionPane.showMessageDialog(null, "Ocorreu um erro na remoção do Jornal.", "Erro de Remoção", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton3ActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    // End of variables declaration//GEN-END:variables

}
